
require 'gtk2'
require 'cookie'


class LinkManager
  
  attr_accessor :treeview, :settings
  
  attr :store
  attr :links
  attr :cookie
  attr :threads
  attr :timer
  
  $name_id = 0
  $url_id = 3
  $status_id = 2
  $progress_id = 1
  
  def initialize(settings)
    @settings = settings
    @store = Gtk::ListStore.new(String, String, String)
    @links = []
    
    @treeview = Gtk::TreeView.new
    renderer = Gtk::CellRendererText.new
    column = Gtk::TreeViewColumn.new("Name", renderer, "text" => $name_id)
    @treeview.append_column(column)
    #    renderer = Gtk::CellRendererText.new
    #    column = Gtk::TreeViewColumn.new("URL", renderer, "text" => $url_id)
    #    @treeview.append_column(column)
    renderer = Gtk::CellRendererText.new
    column = Gtk::TreeViewColumn.new("Status", renderer, "text" => $status_id)
    @treeview.append_column(column)
    renderer = Gtk::CellRendererText.new
    column = Gtk::TreeViewColumn.new("Progress", renderer, "text" => $progress_id)
    @treeview.append_column(column)
    
    
    treeview.model = store
  end
  
  def add_link(url)
    begin
      link = Link.new(url, @settings.download_location)
      @links << link
      iter = store.append
      @store.set_value(iter, $name_id, link.name)
      #      @store.set_value(iter, $url_id, link.url)
      @store.set_value(iter, $status_id, link.status)
      @store.set_value(iter, $progress_id, "#{link.progress.to_s}%")
    rescue RuntimeError
      puts "invalid link : " + line
    end
  end
  
  def clear
    @links = []
    @store.clear
  end
  
  # download all links in queue
  def download_all
    
    if @cookie.nil?
      get_cookie
    end
    puts "total links : #{links.size}"
    
    @links.each { |l| 
      puts "thread start"
      t = Thread.new do
        l.download_start @cookie
      end
    }
    
    #start thread for progress checking
    tracker = Thread.new do
      puts "tracker thread started"
      sleep 2
      while downloads_active? do
        sleep 2
        update_progress
      end
      puts "tracker thread ended"
    end
    
  end
  
  # update the gui with he most recent progress numbers
  def update_progress
    puts "update"
    @links.each_with_index { |l,i| 
      iter = @store.get_iter(i.to_s)
      iter[$progress_id] = "#{l.progress}%"
      iter[$status_id] = l.status
    }
  end
  
  # return true when there are active downloads
  def downloads_active?
    active = false
    @links.each { |l| 
      if l.status == Link::STATUS_DOWNLOADING 
        return true
      end
    }
    return active
  end
  
  # gets cookie from rapidshare server
  def get_cookie
    puts "getting cookie"
    @cookie = Cookie.get(@settings.username, @settings.password)
    puts "cookie received : " + cookie
    # TODO cookie validation
  end
  
  # cancels all running downloads
  def cancel
    links.each { |l| 
      l.cancel
    }
  end
end
